package org.iks.user.aop;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.iks.common.constant.Constant;
import org.iks.common.util.StopWatchUtil;
import org.slf4j.MDC;
import org.springframework.lang.NonNull;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.UUID;

/**
 * Author kzou
 * Date 2024/5/25
 * Description: 全局过滤器
 */
@Slf4j
public class GlobalHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        String requestId = request.getHeader(Constant.RequestId);
        String requestURI = request.getRequestURI();
        String trackId = UUID.randomUUID().toString();
        if (requestId != null) {
            trackId = requestId;
        }
        log.info("receive request {}, parameters: {}", requestURI, request.getParameterMap());
        MDC.put(Constant.RequestId, trackId);
        StopWatchUtil.stopWatch(trackId).start("gateWay");
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) throws Exception {
        StopWatch stopWatch = StopWatchUtil.stopWatch();
        if (stopWatch.isRunning()) {
            stopWatch.stop();
        }
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("the request[{}] total execute time : {}ms, {}",
                request.getRequestURI(),
                totalTimeMillis,
                stopWatch.prettyPrint()
        );
        MDC.clear();
        StopWatchUtil.clearStopWatch();
    }

}
